<template>
  <div class="page-stock-inventory-counting-detail-take-stock new-supplier-mod">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{ $t('takeStock.inventoryDetail') }}
      </div>
    </div>
    <div class="info-title">
      {{ $t('shopProcess.basicInfo') }}
    </div>
    <el-divider />
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      class="form-box"
      label-width="auto"
      @submit.prevent
    >
      <el-form-item
        :label="$t('takeStock.InventoryNo')"
        prop="takeStockNo"
      >
        <span class="table-cell-text line-clamp-one">{{ dataForm.takeStockNo }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('takeStock.InventoryStatus')"
        prop="billStatus"
      >
        <span
          v-if="dataForm.billStatus === 0"
          class="table-cell-text line-clamp-one"
        >{{ $t('takeStock.voided') }}</span>
        <span
          v-if="dataForm.billStatus === 1"
          class="table-cell-text line-clamp-one"
        >{{ $t('takeStock.taking') }}</span>
        <span
          v-if="dataForm.billStatus === 2"
          class="table-cell-text line-clamp-one"
        >{{ $t('takeStock.complete') }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('takeStock.createTime')"
        prop="createTime"
      >
        <span class="table-cell-text line-clamp-one">{{ dataForm.createTime }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('takeStock.regionName')"
        prop="stockRegionName"
      >
        <span class="table-cell-text line-clamp-one">{{ dataForm.stockRegionName || '-' }}</span>
      </el-form-item>
      <el-form-item
        :label="$t('publics.remark')"
        prop="remark"
      >
        <span class="table-cell-text line-clamp-one">{{ dataForm.remark || '-' }}</span>
      </el-form-item>
    </el-form>
    <span class="info-title">{{ $t('group.prodInfo') }}</span>
    <el-divider />
    <!--sku列表-->
    <div class="prod-container">
      <div class="sub-tit">
        {{ $t('takeStock.infoText1') }}{{ takeStockProdItems.length }}{{ $t('takeStock.infoText2') }}{{ totalStock }}{{ $t('takeStock.infoText3') }}{{ profitNum }}{{ $t('takeStock.infoText4') }}{{ lossNum }}{{ $t('takeStock.infoText5') }}
      </div>
      <div class="prodItem-table">
        <!-- 状态导航选择组件 -->
        <statusSelectTabs
          :status-arr="statusArr"
          :default-key="statusArr[0].key"
          @status-change="statusChange"
        >
          <template #export>
            <div
              v-if="isAuth('multishop:takeStockProd:export')"

              @click="getExportExcel"
            >
              {{ $t('takeStock.exportProdDetail') }}
            </div>
          </template>
        </statusSelectTabs>
        <el-table
          :data="totalList.slice((page.currentPage - 1) * page.pageSize, page.currentPage * page.pageSize)"
          header-cell-class-name="table-header"
          row-class-name="table-row"
        >
          <el-table-column
            :label="$t('product.prodName')"
            prop="reason"
            fixed="left"
            align="center"
            width="320px"
          >
            <template #default="scope">
              <div class="prod-info">
                <ImgShow
                  :src="scope.row.pic"
                  :img-style="{width:'60px',height:'60px'}"
                />
                <div class="text">
                  <span class="name">{{ scope.row.prodName }}</span>
                  <span class="name">{{ scope.row.skuName }}</span>
                  <span class="name">{{ scope.row.partyCode }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="bookStock"
            :label="$t('takeStock.bookStock')"
            align="center"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.stocks }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="stock_count"
            align="center"
          >
            <template #header>
              {{ $t('takeStock.profitLossCount') }}
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('takeStock.profitLossTip')"
                placement="top"
              >
                <el-icon><InfoFilled /></el-icon>
              </el-tooltip>
            </template>
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.changeStock > 0 ? '+'+scope.row.changeStock : scope.row.changeStock }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('takeStock.totalStock')"
            prop="totalStock"
            align="left"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.totalStock }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('publics.remark')"
            prop="remark"
            align="left"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.remark || '-' }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page.currentPage"
          :page-size="page.pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalList.length"
          @current-change="onPageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { isAuth } from '@/utils'
import statusSelectTabs from '../components/status-select-tabs.vue'
import { reactive } from 'vue'

const page = reactive({
  currentPage: 1, // 初始页
  pageSize: 10 // 每页数据大小
})
const dataForm = ref({
  takeStockId: null,
  takeStockNo: null,
  billStatus: null,
  createTime: null,
  stockRegionName: null,
  remark: null,
  shopId: null,
  takeStockProdItems: []
})
const takeStockProdItems = ref([])
const totalStock = ref(0) // 实盘库存
let profitCount = 0 // 盘盈
const profitNum = ref(0) // 盘盈件数
let lossCount = 0 // 盘亏
const lossNum = ref(0) // 盘亏件数
let equalCount = 0 // 盘平
let exceptionCount = 0 // 异常
let profitProdList = [] // 盘盈列表
let lossProdList = [] // 盘亏列表
let equalProdList = [] // 盘平列表
let exceptionProdList = [] // 异常列表
const totalList = ref([])
const statusArr = reactive([
  { id: 0, key: 3, label: $t('stock.all') },
  { id: 1, key: 1, label: '' },
  { id: 2, key: 2, label: '' },
  { id: 3, key: 0, label: '' },
  { id: 4, key: -1, label: '' }
]) // 状态导航组件参数
onMounted(() => {
  if (useRoute().query.takeStockId) {
    dataForm.value.takeStockId = useRoute().query.takeStockId
  }
  if (useRoute().query.billStatus) {
    dataForm.value.billStatus = useRoute().query.billStatus
  }
  getDataList()
  getSkuList()
})

const getDataList = () => {
  http({
    url: http.adornUrl('/stock/takeStock/info/' + dataForm.value.takeStockId),
    method: 'get',
    params: http.adornParams({
      takeStockId: dataForm.value.takeStockId
    })
  }).then(({ data }) => {
    dataForm.value = data
  })
}
const getSkuList = () => {
  http({
    url: http.adornUrl('/stock/takeStockProd/list'),
    method: 'get',
    params: http.adornParams(
      {
        takeStockId: dataForm.value.takeStockId
      }
    )
  }).then(({ data }) => {
    takeStockProdItems.value = data
    statusChange(statusArr[0])
    countChange(takeStockProdItems.value)
  })
}
/**
 * 导航选择状态
 */
const statusChange = (item) => {
  totalList.value = []
  switch (item.key) {
    case 1: totalList.value = profitProdList
      break
    case 2: totalList.value = lossProdList
      break
    case 0: totalList.value = equalProdList
      break
    case -1: totalList.value = exceptionProdList
      break
    default: totalList.value = takeStockProdItems.value
      break
  }
  page.currentPage = 1
}
const countChange = (newValue) => {
  profitProdList = []
  lossProdList = []
  equalProdList = []
  exceptionProdList = []
  let _totalStock = 0
  let _profitCount = 0
  let _profitNum = 0
  let _lossCount = 0
  let _lossNum = 0
  let _equalCount = 0
  let _exceptionCount = 0
  newValue.forEach(item => {
    if (!item.totalStock && item.totalStock !== 0) {
      item.totalStock = null
    }
    item.takeStockId = dataForm.value.takeStockId
    item.changeStock = item.totalStock - item.stocks
    _totalStock += item.totalStock
    // ioType 0盘平 1盘盈 2盘亏 -1异常
    switch (item.ioType) {
      case 2 : _lossNum += item.stocks - item.totalStock
        _lossCount++
        lossProdList.push(item)
        break
      case 1 : _profitNum += item.totalStock - item.stocks
        _profitCount++
        profitProdList.push(item)
        break
      case 0 : _equalCount++
        equalProdList.push(item)
        break
      case -1 : _exceptionCount++
        exceptionProdList.push(item)
        break
    }
  })
  totalStock.value = _totalStock
  profitCount = _profitCount
  profitNum.value = _profitNum
  lossCount = _lossCount
  lossNum.value = _lossNum
  equalCount = _equalCount
  exceptionCount = _exceptionCount
  statusArr.forEach(el => {
    if (el.key === 1) {
      el.label = `${$t('takeStock.profit')}(${profitCount})`
    }
    if (el.key === 2) {
      el.label = `${$t('takeStock.loss')}(${lossCount})`
    }
    if (el.key === 0) {
      el.label = `${$t('takeStock.equal')}(${equalCount})`
    }
    if (el.key === -1) {
      el.label = `${$t('takeStock.exception')}(${exceptionCount})`
    }
  })
}
const getExportExcel = () => {
  ElMessageBox.confirm(`${$t('shop.exportProdTip_store')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/stock/takeStockProd/exportTakeStockProd'),
      method: 'get',
      params: http.adornParams({
        takeStockId: dataForm.value.takeStockId
      }),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('takeStock.prodDetailFileName')
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    })
  })
}
const onPageChange = (val) => {
  page.currentPage = val
}

</script>

<style scoped>
div :deep(.is-success .el-input-number__decrease),
div :deep(.is-success .el-input-number__increase),
div :deep(.is-error .el-input-number__decrease),
div :deep(.is-error .el-input-number__increase) {
  right: 1px !important;
}
div :deep(.el-date-editor .el-range-separator) {
  width: 8%;
}
.form-box {
  margin-left: 10px;
}
.info-title {
  color: #333333;
  font-size: 16px;
  font-weight: bold;
}
.prod-info {
  display: flex;
  align-items: center;
}
.prod-info .text {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  margin-left: 10px;
  width: 170px;
}
.prod-info .text .name{
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
  text-align: left;
}
.prod-container .sub-tit{
  font-weight: 600;
  margin-bottom: 8px;
  font-size: 14px;
  color: #323233;
}
</style>
